package com.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.entity.News;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.util.DataSourceUtils;
import com.entity.User;
@WebServlet("/newsmanage")
public class NewsmanageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User manager=(User) session.getAttribute("user");
        if(manager==null)
        {
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                    .forward(req, resp);
        }
        else{
            List<News> items = new ArrayList<>();
            String sql = "SELECT id,name,content,date FROM News";
            try(Connection conn = DataSourceUtils.getConnection();
                PreparedStatement st = conn.prepareStatement(sql);
                ResultSet rs = st.executeQuery()) {
                while (rs.next()) {
                    News item = new News(rs.getInt("id"), rs.getString("name"), rs.getString("content"),rs.getTimestamp("date"));
                    items.add(item);
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            int maxid = 1;
            String sql2="SELECT id FROM News";
            try(Connection conn2 = DataSourceUtils.getConnection();
                PreparedStatement st = conn2.prepareStatement(sql2)){
                try(ResultSet rs = st.executeQuery()){
                    while(rs.next())
                    {
                        int tmp = rs.getInt("id")+1;
                        if(tmp>maxid)maxid=tmp;
                    }
                }
            }catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            req.setAttribute("items", items);
            req.setAttribute("maxid", maxid);
            req.getRequestDispatcher("/WEB-INF/jsp/newsmanage.jsp")
                    .forward(req, resp);
        }
        }
}